package cn.oa.service.impl;
import cn.oa.dao.AttendanceMapper;
import cn.oa.entity.Attendance;
import cn.oa.service.AttendanceService;
import cn.oa.util.DatabaseUtil;
import cn.oa.util.MyBatisUtil;
import cn.oa.util.Page;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Service("attendanceService")
public class AttendanceServiceImpl implements AttendanceService {

    @Resource
    AttendanceMapper attendanceMapper;

    @Override
    public int addSignInByEmployeeId(int employeeId, String date) throws SQLException {
        int result = 0;
        try {
            //查询员工是否有上班打卡记录
            Attendance record = attendanceMapper.getRecordByEmployeeIdAndDate(employeeId, date);
            if (record == null) {
                //执行打卡
                result = attendanceMapper.addSinginByEmployeeId(employeeId);
            } else {
                //已完成上班打卡,不允许重复打卡
                result = 0;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw e;
        }
        return result;
    }

    @Override
    public int addSignOutByEmployeeId(int employeeId, String date) throws SQLException {
        int result = 0;
        try {
            //查询员工是否有上班打卡记录
            Attendance record = attendanceMapper.getRecordByEmployeeIdAndDate(employeeId, date);
            if (record == null) {
                //没有上班打卡记录时不允许执行下班打卡操作
                result = 0;
            } else {
                if (record.getSignOutTime() == null) {
                    //执行下班打卡
                    result = attendanceMapper.updateSingoutByAttendanceId(record.getId());
                } else {
                    result = -2;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw e;
        }
        return result;
    }

    @Override
    public void getAttendancesByPage(String name, String searchDate, Page pageObj) throws SQLException {

        int totalCount = attendanceMapper.getAttendancesCount(name, searchDate);
        pageObj.setTotalCount(totalCount);
        if (totalCount > 0) {
            if (pageObj.getCurrPageNo() > pageObj.getTotalPageCount()) {
                pageObj.setCurrPageNo(pageObj.getTotalPageCount());
            }
            List<Attendance> attendanceList = attendanceMapper.getAttendancesByPage(name, searchDate, pageObj.getCurrPageNo(), pageObj.getPageSize());
            pageObj.setAttendanceList(attendanceList);
        } else {
            pageObj.setCurrPageNo(0);
            pageObj.setAttendanceList(new ArrayList<Attendance>());
        }
    }
}
